const Router = require('koa-router')
// const jwt = require('jsonwebtoken')
const jwt = require('koa-jwt')
// prefix
const router = new Router({ prefix: '/users' })
const { find, findById, create, update, login, checkOwner } = require('../controllers/users')
const { secret } = require('../config')

// 认证
// const auth = async (ctx, next) => {
//   const { authorization } = ctx.request.header
//   const token = authorization.replace('Bearer ', '')
//   try {
//     const user = jwt.verify(token, secret)
//     ctx.state.user = user
//   } catch (error) {
//     ctx.throw(401, error.message)
//   }
//   await next()
// }
const auth = jwt({ secret })
// 查询所有用户
router.get('/', find)

// 新建用户
router.post('/', create)

// 根据 id 查找用户
router.get('/:id', findById)

// 更新用户信息
router.patch('/:id', auth, checkOwner, update)

// 登录
router.post('/login', login)

module.exports = router